package org.androidpush.client;

import android.content.Intent;
import android.util.Log;

import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;

/**
 * Created by huang on 2017/4/20 0020.
 */
public class ChatMsgPacketListener implements PacketListener {

    private static final String LOGTAG = LogUtil
            .makeLogTag(ChatMsgPacketListener.class);

    private final XmppManager xmppManager;

    public ChatMsgPacketListener(XmppManager xmppManager) {
        this.xmppManager = xmppManager;
    }

    @Override
    public void processPacket(Packet packet) {
        Log.d(LOGTAG, "ChatMsgPacketListener.processPacket()...");
        Log.d(LOGTAG, "packet.toXML()=" + packet.toXML());

        if (packet instanceof ChatMsgIQ) {
            ChatMsgIQ chatMsgIQ = (ChatMsgIQ) packet;

            if (chatMsgIQ.getChildElementXML().contains(
                    "androidpn:iq:chatmsg")) {
                String chatToUser = chatMsgIQ.getTouser();
                String chatFromUser = chatMsgIQ.getFromuser();
                String chatDate = chatMsgIQ.getDate();
                String chatMessage = chatMsgIQ.getMessage();
                String chatuuid = chatMsgIQ.getUuid();
                String chatType = chatMsgIQ.getMsgtype();

                Intent intent = new Intent(Constants.ACTION_SHOW_CHATMSG);
                intent.putExtra(Constants.CHATMSG_TOUSER, chatToUser);
                intent.putExtra(Constants.CHATMSG_FROMUSER, chatFromUser);
                intent.putExtra(Constants.CHATMSG_DATE, chatDate);
                intent.putExtra(Constants.CHATMSG_MESSAGE, chatMessage);
                intent.putExtra(Constants.CHATMSG_TYPE, chatType);

                xmppManager.getContext().sendBroadcast(intent);

                DeliverConfirmIQ deliverConfirmIQ = new DeliverConfirmIQ();
                deliverConfirmIQ.setUuid(chatuuid);
                deliverConfirmIQ.setType(IQ.Type.SET);

                xmppManager.getConnection().sendPacket(deliverConfirmIQ);
            }
        }
    }
}
